package com.example.webdome.util;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

import static com.example.webdome.util.RedisConstants.ONLINE_USERS;

@Component
public class OnlineUserStatsService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    String key=ONLINE_USERS;
    /**
     * 添加用户在线信息
     * @param userId
     * @return
     */
    public Boolean online(Integer userId){
        return this.stringRedisTemplate.opsForZSet().add(key, userId.toString(), Instant.now().toEpochMilli());
    }
    public void outOnline(Integer userId){
       stringRedisTemplate.opsForZSet().remove(key,userId.toString());
    }
    /**
     * 获取一定时间内，在线的用户数量
     * @param duration
     * @return
     */
    public Long count(Duration duration) {
        LocalDateTime now = LocalDateTime.now();
        return this.stringRedisTemplate.opsForZSet().count(ONLINE_USERS,
                now.minus(duration).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(),
                now.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
    }
    /**
     * 获取所有在线过的用户数量，不论时间
     * @return
     */
    public Long count() {
        return this.stringRedisTemplate.opsForZSet().zCard(ONLINE_USERS);
    }
    /**
     * 清除超过一定时间没在线的用户数据
     * @param duration
     * @return
     */
    public Long clear(Duration duration) {
        return this.stringRedisTemplate.opsForZSet().removeRangeByScore(ONLINE_USERS, 0,
                LocalDateTime.now().minus(duration).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
    }
}
